import { fileIo as fs } from '@kit.CoreFileKit';
import { buffer } from "@kit.ArkTS";

/**
 * @internal
 */
export const calculateBodyLength = (body: any): number | undefined => {
  if (!body) {
    return 0;
  }
  if (typeof body === "string") {
    return buffer.byteLength(body);
  } else if (typeof body.byteLength === "number") {
    // handles Uint8Array, ArrayBuffer, Buffer, and ArrayBufferView
    return body.byteLength;
  } else if (typeof body.size === "number") {
    return body.size;
  } else if (typeof body.start === "number" && typeof body.end === "number") {
    return body.end + 1 - body.start;
  } else if (typeof body.path === "string" || buffer.isBuffer(body.path)) {
    // handles fs readable streams
    return fs.lstatSync(body.path).size;
    // return lstatSync(body.path).size;
  } else if (typeof body.fd === "number") {
    // handles fd readable streams
    return fs.statSync(body.fd).size
    // return fstatSync(body.fd).size;
  }
  throw new Error(`Body Length computation failed for ${body}`);
};
